package com.xqkad.myplayer.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.xqkad.myplayer.MediaAidlInterface;
import com.xqkad.myplayer.R;
import com.xqkad.myplayer.fragment.TabFragment;
import com.xqkad.myplayer.service.BroadcastService;
import com.xqkad.myplayer.service.MediaService;
import com.xqkad.myplayer.service.MusicPlayer;
import com.xqkad.myplayer.utils.AudioTools;
import com.xqkad.myplayer.utils.PreferencesUtility;

import java.util.List;

public class PlayingActivity extends ReceiverActivity implements View.OnClickListener{
    //region UI
    private ImageView mPlayingmode, mControl, mNext, mPre, mPlaylist;
    private TextView mTitle, mTime;
    private SeekBar mProgress;
    //endregion
    private boolean mProgressTouching = false;
    private Handler handler = new Handler();
    private ServiceConnection conn;
    //region updateProgress
    private Runnable updateProgress = new Runnable() {
        @Override
        public void run() {
            int pos = MusicPlayer.getCurrentPosition();
            int dur = MusicPlayer.getDuration();
            int progress = 0;
            String time = "00:00/00:00";
            if(pos != -1 && dur > 0){
                time = AudioTools.makeTimeString(pos)+"/"+AudioTools.makeTimeString(dur);
                progress = pos * 100 / dur;
            }
            mTime.setText(time);
            if(!mProgressTouching)
                mProgress.setProgress(progress);
            if(MusicPlayer.isPlaying()) {
                handler.removeCallbacks(updateProgress);
                handler.postDelayed(updateProgress, 1000);
            }
        }
    };
    //endregion

    //region 生命周期 方法
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);
        if(!AudioTools.checkPermission(this))
            requestPermission();
        conn = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //log("ac bind"+(MusicPlayer.mService==null));
                MusicPlayer.mService = MediaAidlInterface.Stub.asInterface(service);
                updateUI();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                MusicPlayer.mService = null;
                //log("ac unbind");
            }
        };
        MusicPlayer.bindService(this, conn);
        setTabPageFragment();
        init();
        getSupportActionBar().hide();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(updateProgress);
    }

    @Override
    protected void onDestroy() {
        //log("playing onDestroy");
        super.onDestroy();
        MusicPlayer.unbindService(this,conn);
    }
    //endregion

    private void setTabPageFragment() {
        TabFragment fragment = TabFragment.newInstance();
        FragmentTransaction transAction = getSupportFragmentManager().beginTransaction();
        transAction.add(R.id.TabPager_Container, fragment);
        transAction.commitAllowingStateLoss();
    }

    private void init(){
        mPlayingmode = (ImageView) findViewById(R.id.playing_mode);
        mControl = (ImageView) findViewById(R.id.playing_play);
        mNext = (ImageView) findViewById(R.id.playing_next);
        mPre = (ImageView) findViewById(R.id.playing_pre);
        mPlaylist = (ImageView) findViewById(R.id.playing_playlist);
        mTitle = (TextView)findViewById(R.id.music_title);
        mTime = (TextView) findViewById(R.id.music_duration);
        mProgress = (SeekBar) findViewById(R.id.play_seek);

        mPlayingmode.setOnClickListener(this);
        mControl.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mPre.setOnClickListener(this);
        mPlaylist.setOnClickListener(this);
        mProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //Log.d(TAG, "Changed: "+progress+" "+fromUser);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mProgressTouching = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int i = mProgress.getProgress();
                int dur = MusicPlayer.getDuration();
                if(i >= 0 && dur != -1){
                    MusicPlayer.seek(i * dur / 100);
                    mProgressTouching = false;
                }
                //Log.d(TAG, "onStopTouch: ");
            }
        });
    }

    //call on resume  onbind receive playmode
    private void updateUI(){
        //Log.d(TAG, "updateUI: mService is "+(MusicPlayer.mService==null ? "null" : "has"));
        String title = MusicPlayer.getTitle();
        mTitle.setText(""+title);
        handler.post(updateProgress);
        if(MusicPlayer.isPlaying()){
            mControl.setImageResource(R.drawable.play_btn_pause);
        }else{
            mControl.setImageResource(R.drawable.play_rdi_btn_play);
        }
        int m = MusicPlayer.getPlayMode();
        if(m==0){
            mPlayingmode.setImageResource(R.drawable.play_icn_loop_prs);
        }else if(m==1){
            mPlayingmode.setImageResource(R.drawable.play_icn_one_prs);
        }else if(m==2){
            mPlayingmode.setImageResource(R.drawable.play_icn_shuffle);
        }
    }

    @Override
    public void onClick(View v) {
        //Log.d(TAG, "onClick: PPre");
        switch (v.getId()){
            case R.id.playing_mode:
                int m = MusicPlayer.getPlayMode();
                if(m!=-1){
                    MusicPlayer.setPlayMode(m==2?0:m+1);
                }
                break;
            case R.id.playing_pre:
                MusicPlayer.previous();
                break;
            case R.id.playing_play:
                if(MusicPlayer.isPlaying()){
                    MusicPlayer.pause();
                }else{
                    MusicPlayer.play();
                }
                break;
            case R.id.playing_next:
                MusicPlayer.next();
                break;
            case R.id.playing_playlist:
                MusicPlayer.playlist();
                break;
        }
    }

    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        final String action = intent.getAction();
        //Log.d("mytag", "onReceive: "+action);
        if(ON_PLAY.equals(action) ||
                ON_PAUSE.equals(action) ||
                ON_STOP.equals(action) ||
                ON_PLAYMODE_CHANGE.equals(action)){
            updateUI();
        }
    }

    private void requestPermission(){
        ActivityCompat.requestPermissions(this
                ,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}
